package P3排序算法;

import java.util.Arrays;

/*
归并排序（二路归并）
O(N logN)
S(N)
稳定
特点：二分区间/四分区间/八分区间 有序的
*/
public class MergeSort {
    public static void main(String[] args) {
        int[] arr = {9, 1, 8, 2, 7, 3, 6, 4, 5};
        mergeSort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }

    public static void mergeSort(int[] arr, int L, int R) {
        if (L >= R) {
            return;
        }
        int mid = (L + R) / 2;
        mergeSort(arr, L, mid);
        mergeSort(arr, mid + 1, R);
        if (arr[mid] > arr[mid + 1]) {
            merge(arr, L, mid, R);
        }
    }

    private static void merge(int[] arr, int l, int mid, int r) {
        int[] aux = new int[r - l + 1];
        for (int i = l; i <= r; i++) {
            aux[i - l] = arr[i];
        }
        int p1 = l;
        int p2 = mid + 1;
        int p3 = l;
        while (p3 <= r) {
            if (p1 > mid) {
                arr[p3] = aux[p2 - l];
                p2++;
            } else if (p2 > r) {
                arr[p3] = aux[p1 - l];
                p1++;
            } else if (aux[p1 - l] < aux[p2 - l]) {
                arr[p3] = aux[p1 - l];
                p1++;
            } else {
                arr[p3] = aux[p2 - l];
                p2++;
            }
            p3++;
        }
    }
}